import { Injectable } from '@nestjs/common';
import { CreateBlogDto } from './dto/create-blog.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like, In } from 'typeorm';
import { blog } from '../../entities/blog.entity';
import { tag } from '../../entities/tag.entity';
import * as moment from 'moment';
import { v4 as uuidv4 } from 'uuid';
import { API, BlogAPI } from '../../types';
import { generateAiMessage } from "../../utils/tool";

@Injectable()
export class BlogService {
  constructor(
    @InjectRepository(blog)
    private readonly blog: Repository<blog>,
    @InjectRepository(tag)
    private readonly tag: Repository<tag>,
  ) {}

  async create(createBlogDto: CreateBlogDto) {
    const { title, content, tagIds, banner, head, id, dimension, isAiSummary } = createBlogDto;
    const tags = await this.tag.find({
      where: {
        id: In(tagIds.split(',')),
      },
    });
    const insertId = uuidv4();
    if (isAiSummary === true) {
      /// 异步执行Ai总结
      this.setBlogAiSummary({
        content: content,
        id: id || insertId
      })
    }
    delete createBlogDto.isAiSummary;
    const tagString = tags.map((el) => el.name).join(',');
    // 传递id则执行修改
    if (id) {
      await this.updateBlog({
        id,
        createBlogDto: createBlogDto,
        tags: tagString,
      });
      return { message: '修改成功' };
    }
    await this.blog.insert({
      id: insertId,
      title,
      content,
      tagIds,
      banner,
      head,
      dimension,
      tags: tagString,
      creationTime: moment().valueOf(),
      updateTime: moment().valueOf(),
    });
    return { message: '添加成功' };
  }

  // 设置AI总结
  async setBlogAiSummary(options: {
    content: string,
    id: string,
  }) {
    const res = await generateAiMessage(options.content);
    await this.blog.update(
      { id: options.id },
      {
        aiSummary: res
      },
    );
  }

  // 更新博客
  async updateBlog(options: {
    createBlogDto: CreateBlogDto,
    tags: string,
    id: string
  }) {
    const {createBlogDto, id, tags} = options;
    return this.blog.update(
      { id },
      {
        ...createBlogDto,
        tags: tags,
        updateTime: moment().valueOf(),
      },
    );
  }

  async findAll(query: API.paging & BlogAPI.blogTableSearch) {
    const { current = 1, pageSize = 15, title = '', banner } = query;
    const [users, total] = await this.blog.findAndCount({
      skip: (current - 1) * pageSize,
      take: pageSize,
      where: {
        title: Like(`%${title}%`),
        banner,
      },
      order: {
        updateTime: 'DESC',
      },
    });
    return {
      list: users.map((el) => {
        return {
          ...el,
          creationTime: moment(Number(el.creationTime)).format(
            'YYYY-MM-DD HH:mm:ss',
          ),
          updateTime: moment(Number(el.updateTime)).format(
            'YYYY-MM-DD HH:mm:ss',
          ),
        };
      }),
      total,
    };
  }

  findOne(id: string) {
    return this.blog.findOne({
      where: {
        id,
      },
    });
  }

  async updateBanner(body: { id: string; banner: 1 | 0 }) {
    const { id, banner } = body;
    await this.blog.update(
      { id },
      {
        banner,
      },
    );
  }

  async updateSideRecommend(body: { id: string; sideRecommend: 1 | 0 }) {
    const { id, sideRecommend } = body;
    await this.blog.update(
      { id },
      {
        sideRecommend,
      },
    );
  }

  async remove(id: string) {
    await this.blog.delete({ id });
    return { message: '删除成功' };
  }
}
